import 'package:flutter/material.dart';
import 'package:qgchat/http/apis/user.dart';
import 'package:qgchat/http/models/anchorInfoModel.dart';
import 'package:qgchat/http/models/getalipayModel.dart';
import 'package:qgchat/http/models/userInfoModel.dart';
import 'package:shared_preferences/shared_preferences.dart';

import '../../common/global/global.dart';

class UserState with ChangeNotifier {
  /// 用户登录凭证
  String token;

  /// 用户信息
  UserInfoModel info;

  /// 主播信息
  AnchorInfoModel anchorInfo;

  /// 用户支付宝信息
  GetalipayModel alipay;

  /// 销毁所有全局量
  disposeAll() {
    token = null;
    info = null;
    anchorInfo = null;
    alipay = null;
    cache?.remove("token");
    notifyListeners();
  }

  /// 登录
  login(val) {
    token = val;
    cache.setString("token", val);
    notifyListeners();
  }

  /// 注销
  logout() {
    disposeAll();
    goLogin();
  }

  /// 获取用户信息
  userInfo({callback}) async {
    final token = cache.getString('token');
    if (token == null) return;
    UserInfoModel res = await UserApis.myInfo();
    if (res != null) {
      info = res;
      if (callback != null) {
        callback(res);
      }
      Map userInfo = res.toJson();
      cache.setString("userinfo", toJson(userInfo));
      notifyListeners();
    }
    if (res.memberType == 1) {
      anchorInfo = await UserApis.getAnchorInfo(res.memberToken);
      notifyListeners();
    }
    return res;
  }

  /// 获取支付宝信息
  alipayInfo({callback}) async {
    GetalipayModel res = await UserApis.getalipay();
    alipay = res;
    if (callback != null) {
      callback(res);
    }
    notifyListeners();
    return res;
  }

  /// 初始化app
  Future initApp(String token) async {
    final prefs = await SharedPreferences.getInstance();
    prefs.setString("token", token);

    UserApis.getalipay().then((alipay) {
      alipay = alipay;
      notifyListeners();
    });
    info = await UserApis.myInfo();
    if (info?.memberType == 1) {
      anchorInfo = await UserApis.getAnchorInfo(info.memberToken);
    }

    Map userInfo = info.toJson();
    prefs.setString("userinfo", toJson(userInfo));

    notifyListeners();
    return info;
  }

  // 勿扰
  disturb(int isopen) {
    info.disturb = isopen;
    notifyListeners();
  }
}
